import { InputSampler } from './InputSampler';

export type FrameInput = {
    tick: number;
    bitmask: number; // 按键位域
};

export type Meta = {
    fixedDelta: number;
    seed: number;
};

// 记录类
export class Recorder {
    private frames: FrameInput[] = [];
    constructor(private sampler: InputSampler, private meta: Meta) {}

    sample(tick: number) {
        const bitmask = this.sampler.sampleMask();
        this.frames.push({ tick, bitmask });
    }

    replay(tick: number) {
        if (this.frames && tick >= this.frames.length) {
            console.log('end');
            return;
        }

        const mask = this.frames[tick];
        const sample = this.sampler.virtualSample(mask.bitmask);
        this.sampler.sampler = sample;
    }

    exportData() {
        return {
            meta: this.meta,
            frames: this.frames,
        };
    }

    exportJson() {
        return JSON.stringify(this.exportData());
    }

    load(json: string) {
        console.log('json', json);
        try {
            let obj = JSON.parse(json);
            this.meta = obj.meta;
            this.frames = obj.frames;
        } catch (e) {
            console.error(e);
        }
    }
}
